package com.xhwl.logistics.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.common.dto.cent.vehicle.SupplierConfigDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.vehicle.ParkSupplierEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.cent.device.Device;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.query.cent.device.DeviceQuery;
import com.xhwl.common.query.cent.device.ProductAccessQuery;
import com.xhwl.logistics.service.cent.IDeviceService;
import com.xhwl.logistics.service.cent.IProductAccessCentService;
import com.xhwl.logistics.strategy.InfoSyncSupplierStrategy;
import com.xhwl.logistics.strategy.context.InfoSyncSupplierStrategyContext;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p></p>
 *
 * @Author: zsm
 * @Date: 2021-05-31
 */
@Slf4j
//@Component
//@Deprecated
public class JobHandler extends IJobHandler {

    @Autowired
    private InfoSyncSupplierStrategyContext infoSyncSupplierStrategyContext;

    @Autowired
    private IProductAccessCentService productAccessCentService;

    @Autowired
    private IDeviceService deviceService;

//    @Override   //xxl-job版本从2.2.0升级到2.3.0，因此IJobHandler重写的execute方法返回值和入参都会改变
//    public void execute() throws Exception {
//
//    }
    @XxlJob("sMessageJobHandler")   //xxl-job版本从2.3.0降到2.2.0，因此IJobHandler重写的execute方法返回值和入参都会改变
    @Override
    public ReturnT<String> execute(String param) throws Exception {
        log.info("参数：{}",param);
        for (int i = 0; i < 10; i++) {
            System.out.println("执行任务了............................1234");
            Thread.sleep(1000);
        }
        return ReturnT.SUCCESS;
    }


    /**
     * 更新车场设备状态
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("updateParkDeviceStatusHandler")
    public ReturnT<String> updateParkDeviceStatus(String param) throws Exception {
        log.info("车场参数id：{}",param);
        //param以项目id+”-“+车场id+业态id拼接 若多种组合就以逗号拼接  如1258-592011253-1
        String[] split = param.split(",");
        List<String> list = Arrays.asList(split);
        list.forEach(l->{
            List<String> asList = Arrays.asList(l.split("-"));
            Integer projectId = Integer.valueOf(asList.get(0));
            String parkId = asList.get(1);
            Short industryId = Short.valueOf(asList.get(2));
            //先根据项目id和产品分类id查询供应商
            List<DeviceProjSupplierCategory> deviceProjSupplierCategories = productAccessCentService.listProductAccess(industryId, new ProductAccessQuery(projectId, CategoryEnum.YARD_GATE.getId()));
            if (deviceProjSupplierCategories.isEmpty()) {
                throw new BusinessException("该项目未配置供应商，请先配置");
            }
            DeviceProjSupplierCategory productAccess = deviceProjSupplierCategories.get(0);
            JSONObject properties = productAccess.getProperties();
            //获取供应商配置信息
            SupplierConfigDTO supplierConfigDTO = JSON.toJavaObject(properties, SupplierConfigDTO.class);
            //根据supplierId以及策略模式选取对应的接口实现类
            Integer supplierId = productAccess.getSupplierId();
            InfoSyncSupplierStrategy infoSyncSupplierService = infoSyncSupplierStrategyContext.getInfoSyncSupplierService(ParkSupplierEnum.getParkSupplierEnum(supplierId));
            //DeviceDTO deviceDTO =new DeviceDTO();
            //deviceDTO.setParkId(parkId);
            Map<String, Object> map = new HashMap<>();
            map.put("parkId",parkId);
            List<Device> listFromSupplier = infoSyncSupplierService.getParkingLotDevice(map, supplierConfigDTO);
            if (listFromSupplier.isEmpty()) {
                throw new BusinessException("查询供应商，无相关设备信息");
            }
            List<String> thirdDeviceIdsFromSupplier = listFromSupplier.stream().map(a -> a.getThirdDeviceId()).collect(Collectors.toList());
            DeviceQuery query = new DeviceQuery();
            query.setProjectId(projectId);
            query.setThirdDeviceIdList(thirdDeviceIdsFromSupplier);
            List<com.xhwl.common.dto.cent.device.DeviceDTO> listFromDB = deviceService.list(industryId, query);
            if (null!=listFromDB) {
                //更新设备状态
                listFromDB.forEach(lBD->{
                    listFromSupplier.forEach(lSP->{
                        if (lSP.getThirdDeviceId().equals(lBD.getThirdDeviceId())) {
                            lBD.setOnlineStatus(lSP.getOnlineStatus().id);
                        }
                    });
                });
            }
            deviceService.batchUpdate(industryId,listFromDB);

        });


        return ReturnT.SUCCESS;
    }

}
